import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.util.*;

import javax.swing.*;
import javax.swing.table.*;

import java.awt.event.*;

public class GUI {

	/**
	 * GUI Variables
	 */
	private JFrame frmDatabaseOfBadassery;
	private JTextField wpnNameText;
	private JTextField wpnTypeText;
	private JTextField wpnModText;
	private JTextField wpnAttText;
	private JTextField wpnDmgText;
	private JTextField wpnWeightText;
	private JTextField wpnValueText;
	private JPanel display_panel;
	private JTable resultTable;
	private boolean urlEnabled;
	private String[] getText;
	private DefaultTableModel model;
	private static int numRows = 0;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GUI window = new GUI();
					window.frmDatabaseOfBadassery.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public GUI() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {

		frmDatabaseOfBadassery = new JFrame();
		frmDatabaseOfBadassery.setResizable(false);
		frmDatabaseOfBadassery.setTitle("Database of Badassery");
		frmDatabaseOfBadassery.setBounds(100, 100, 1050, 550);
		frmDatabaseOfBadassery.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmDatabaseOfBadassery.getContentPane().setLayout(new BorderLayout(0, 0));

		JPanel north_panel = new JPanel();
		frmDatabaseOfBadassery.getContentPane().add(north_panel, BorderLayout.NORTH);

		JLabel titleLabel = new JLabel("Database Of Badassery");
		titleLabel.setFont(new Font("Old English Text MT", Font.BOLD, 32));
		titleLabel.setForeground(Color.RED);
		north_panel.add(titleLabel);

		final JPanel center_panel = new JPanel();
		frmDatabaseOfBadassery.getContentPane().add(center_panel, BorderLayout.CENTER);
		center_panel.setLayout(new BorderLayout(0, 0));

		display_panel = new JPanel();
		resultTable = new JTable() {
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {                
				return false;              
			};
		};
		resultTable.setFillsViewportHeight(true);
		display_panel.add(resultTable);
		center_panel.add(display_panel, BorderLayout.CENTER);

		JPanel west_panel = new JPanel();
		frmDatabaseOfBadassery.getContentPane().add(west_panel, BorderLayout.WEST);
		west_panel.setLayout(new BoxLayout(west_panel, BoxLayout.Y_AXIS));

		JPanel weaponNamePanel = new JPanel();
		west_panel.add(weaponNamePanel);
		weaponNamePanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel wpnNameLabel = new JLabel("Weapon Name");
		wpnNameLabel.setHorizontalAlignment(SwingConstants.CENTER);
		weaponNamePanel.add(wpnNameLabel);

		wpnNameText = new JTextField();
		weaponNamePanel.add(wpnNameText);
		wpnNameText.setColumns(10);

		JPanel weaponTypePanel = new JPanel();
		west_panel.add(weaponTypePanel);

		JLabel wpnTypeLabel = new JLabel("Weapon Type");
		weaponTypePanel.add(wpnTypeLabel);

		wpnTypeText = new JTextField();
		wpnTypeText.setColumns(10);
		weaponTypePanel.add(wpnTypeText);

		JPanel weaponModPanel = new JPanel();
		west_panel.add(weaponModPanel);

		JLabel wpnModLabel = new JLabel("Weapon Modifier");
		weaponModPanel.add(wpnModLabel);

		wpnModText = new JTextField();
		wpnModText.setColumns(10);
		weaponModPanel.add(wpnModText);		

		JPanel weaponAttPanel = new JPanel();
		west_panel.add(weaponAttPanel);

		JLabel wpnAttLabel = new JLabel("Weapon Attribute");
		weaponAttPanel.add(wpnAttLabel);

		wpnAttText = new JTextField();
		wpnAttText.setColumns(10);
		weaponAttPanel.add(wpnAttText);

		JPanel weaponDmgPanel = new JPanel();
		west_panel.add(weaponDmgPanel);

		JLabel wpnDmgLabel = new JLabel("Weapon Damage");
		weaponDmgPanel.add(wpnDmgLabel);

		final JComboBox<String> wpnDmgCombo = new JComboBox<String>();
		wpnDmgCombo.setModel(new DefaultComboBoxModel<String>(new String[] {"=", "<", ">"}));
		weaponDmgPanel.add(wpnDmgCombo);

		wpnDmgText = new JTextField();
		wpnDmgText.setColumns(10);
		weaponDmgPanel.add(wpnDmgText);

		JPanel weaponWeightPanel = new JPanel();
		west_panel.add(weaponWeightPanel);

		JLabel wpnWeightLabel = new JLabel("Weapon Weight");
		weaponWeightPanel.add(wpnWeightLabel);

		final JComboBox<String> wpnWeightCombo = new JComboBox<String>();
		wpnWeightCombo.setModel(new DefaultComboBoxModel<String>(new String[] {"=", "<", ">"}));
		weaponWeightPanel.add(wpnWeightCombo);

		wpnWeightText = new JTextField();
		wpnWeightText.setColumns(10);
		weaponWeightPanel.add(wpnWeightText);

		JPanel weaponValuePanel = new JPanel();
		west_panel.add(weaponValuePanel);

		JLabel wpnValueLabel = new JLabel("Weapon Value");
		weaponValuePanel.add(wpnValueLabel);

		final JComboBox<String> wpnValueCombo = new JComboBox<String>();
		wpnValueCombo.setModel(new DefaultComboBoxModel<String>(new String[] {"=", "<", ">"}));
		weaponValuePanel.add(wpnValueCombo);

		wpnValueText = new JTextField();
		wpnValueText.setColumns(10);
		weaponValuePanel.add(wpnValueText);

		JPanel weaponRarityPanel = new JPanel();
		west_panel.add(weaponRarityPanel);

		JLabel wpnRarityLabel = new JLabel("Weapon Rarity");
		weaponRarityPanel.add(wpnRarityLabel);

		final JComboBox<String> wpnRarityCombo = new JComboBox<String>();
		wpnRarityCombo.setForeground(Color.BLACK);
		wpnRarityCombo.setModel(new DefaultComboBoxModel<String>(new String[] {"All", "Uncommon", "Common", "Rare", "Legendary"}));
		weaponRarityPanel.add(wpnRarityCombo);

		JPanel sortByPanel = new JPanel();
		west_panel.add(sortByPanel);

		JLabel sortByLabel = new JLabel("Sort By");
		sortByPanel.add(sortByLabel);

		final JComboBox<String> sortByCombo = new JComboBox<String>();
		sortByCombo.setModel(new DefaultComboBoxModel<String>(new String[] {"Name", "Type", "Damage", "Weight", "Value", "Rarity"}));
		sortByPanel.add(sortByCombo);

		JPanel queryTimePanel = new JPanel();
		west_panel.add(queryTimePanel);

		//testOnStartup(resultTable, display_panel);

		final JLabel queryTime = new JLabel("Query time: ");
		queryTimePanel.add(queryTime);

		final JPanel queryItemsPanel = new JPanel();
		west_panel.add(queryItemsPanel);

		final JLabel queryItemsNum = new JLabel("Total items: ");
		queryItemsPanel.add(queryItemsNum);

		JPanel urlPanel = new JPanel();
		west_panel.add(urlPanel);

		final JPanel url_textbox = new JPanel();
		final JTextArea url_text = new JTextArea("http://www2.hawaii.edu/~alanho/ItemGenerator.txt");

		JButton enableURLButton = new JButton("Enable URL");
		enableURLButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				url_textbox.removeAll();
				JLabel lblNewLabel = new JLabel("Enter URL: ");
				url_textbox.add(lblNewLabel);

				url_textbox.add(url_text);
				url_text.setColumns(50);

				center_panel.add(url_textbox, BorderLayout.SOUTH);
				center_panel.revalidate();

				urlEnabled = true;
			}
		});
		urlPanel.add(enableURLButton);

		JButton disableURLButton = new JButton("Disable URL");
		disableURLButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				urlEnabled = false;
				//Uncomment to remove text when Enable/Disable buttons are pressed, otherwise whatever text there is stays there
				//url_text.setText("");
				url_textbox.removeAll();
				url_textbox.revalidate();

			}
		});
		urlPanel.add(disableURLButton);

		JPanel generateResultPanel = new JPanel();
		west_panel.add(generateResultPanel);

		JButton genResultButton = new JButton("Generate Results");
		genResultButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				long sortTime = System.currentTimeMillis();  //start time

				// JDBC VARIABLES
				String urlPrefix = "jdbc:mysql:";
				String url = urlPrefix + "//ec2-23-21-211-172.compute-1.amazonaws.com:3306/ockbdb";
				String user = "ockbadmin";
				String password = "ics414ockb";
				Connection con;
				Statement stmt;
				ResultSet rs;
				String query = "SELECT Name, Type, Damage, Weight, Value, Rarity FROM weapons WHERE ";

				// JDBC VARIABLES
				String wpnNameParse = wpnNameText.getText();
				String wpnTypeParse = wpnTypeText.getText();
				String wpnModParse = wpnModText.getText();
				String wpnAttParse = wpnAttText.getText();
				String wpnDmgParse = wpnDmgText.getText();
				String wpnWeightParse = wpnWeightText.getText();
				String wpnValueParse = wpnValueText.getText();

				//Get combo box items
				String wpnDmgEquality = (String) wpnDmgCombo.getSelectedItem();
				String wpnWeightEquality = (String) wpnWeightCombo.getSelectedItem();
				String wpnValueEquality = (String) wpnValueCombo.getSelectedItem();
				String wpnRarityType = (String) wpnRarityCombo.getSelectedItem();
				String sortBy = (String) sortByCombo.getSelectedItem();

				if(urlEnabled) {

					String urlText = url_text.getText();
					getText = new String[12];

					for(int i = 0; i < getText.length; i++) {
						getText[i] = "";
					}

					getText[0] = wpnNameParse;
					getText[1] = wpnTypeParse;
					getText[2] = wpnModParse;
					getText[3] = wpnAttParse;
					getText[4] = wpnDmgEquality;
					getText[5] = wpnDmgParse;
					getText[6] = wpnWeightEquality;
					getText[7] = wpnWeightParse;
					getText[8] = wpnValueEquality;
					getText[9] = wpnValueParse;
					getText[10] = wpnRarityType;
					getText[11] = sortBy;

					//No input in textbox
					if(urlText.equals("")) {
						JOptionPane.showMessageDialog(null, "There was no input!");
					} else {
						createList(urlText);
					}

					//Parse input in URL textbox

					//Valid input in URL textbox

					//Invalid input in URL textbox


					sortTime = System.currentTimeMillis() - sortTime;  //duration = end - start time
					//JOptionPane.showMessageDialog(null, "Total query time " + sortTime + " milliseconds.");
					queryTime.setText("Query time: " + sortTime + " milliseconds");
					queryItemsNum.setText("Total items: " + model.getRowCount());

				} else {
					// JDBC CONNECTION AND QUERY
					try
					{                     

						// Load the driver
						Class.forName("com.mysql.jdbc.Driver");
						System.out.println("**** Loaded the JDBC driver");

						// Create the connection using the IBM Data Server Driver for JDBC and SQLJ
						con = DriverManager.getConnection (url, user, password);
						// Commit changes automatically
						con.setAutoCommit(true);
						System.out.println("**** Created a JDBC connection to the data source");

						// Create the Statement
						stmt = con.createStatement();
						System.out.println("**** Created JDBC Statement object");


						//Check if these three text boxes contain non-integer values.
						if (!wpnDmgText.getText().equals(""))
						{
							Integer.parseInt(wpnDmgText.getText());
						}
						if (!wpnWeightText.getText().equals(""))
						{
							Integer.parseInt(wpnWeightText.getText());
						}
						if (!wpnValueText.getText().equals(""))
						{
							Integer.parseInt(wpnValueText.getText());
						}

						//////////////////////////////////////////////
						//                                          //
						//                                          //
						// GENERATE QUERY HERE                      //
						//                                          //
						//                                          //
						//////////////////////////////////////////////

						if (!wpnNameParse.equals(""))
						{
							query = query + "Name LIKE " + "'%" + wpnNameParse + "%'";
						}
						if (!wpnTypeParse.equals(""))
						{
							if (!query.substring(query.length()-6, query.length()).equals("WHERE "))
							{
								query = query + " AND ";
							}
							query = query + "Type LIKE " + "'%" + wpnTypeParse + "%'";
						}
						if (!wpnModParse.equals(""))
						{
							if (!query.substring(query.length()-6, query.length()).equals("WHERE "))
							{
								query = query + " AND ";
							}
							query = query + "Modifier LIKE " + "'%" + wpnModParse + "%'";
						}
						if (!wpnAttParse.equals(""))
						{
							if (!query.substring(query.length()-6, query.length()).equals("WHERE "))
							{
								query = query + " AND ";
							}
							query = query + "Attribute LIKE " + "'%" + wpnAttParse + "%'";
						}
						if (!wpnDmgParse.equals(""))
						{
							if (!query.substring(query.length()-6, query.length()).equals("WHERE "))
							{
								query = query + " AND ";
							}
							query = query + "Damage " + wpnDmgEquality + " " + wpnDmgParse;
						}
						if (!wpnWeightParse.equals(""))
						{
							if (!query.substring(query.length()-6, query.length()).equals("WHERE "))
							{
								query = query + " AND ";
							}
							query = query + "Weight " + wpnWeightEquality + " " + wpnWeightParse;
						}
						if (!wpnValueParse.equals(""))
						{
							if (!query.substring(query.length()-6, query.length()).equals("WHERE "))
							{
								query = query + " AND ";
							}
							query = query + "Value " + wpnValueEquality + " " + wpnValueParse;
						}
						if (!wpnRarityType.equals("All"))
						{
							if (!query.substring(query.length()-6, query.length()).equals("WHERE "))
							{
								query = query + " AND ";
							}
							query = query + "Rarity = " + "'" + wpnRarityType + "'";
						}

						if (query.equals("SELECT Name, Type, Damage, Weight, Value, Rarity FROM weapons WHERE "))
						{
							query = "SELECT Name, Type, Damage, Weight, Value, Rarity FROM weapons";
						}

						query = query + " ORDER BY " + sortBy + " ASC";

						query = query + ";";
						System.out.println(query);

						// Execute a query and generate a ResultSet instance
						rs = stmt.executeQuery(query);
						System.out.println("**** Created JDBC ResultSet object");

						//////////////////////////////////////////////
						//                                          //
						//                                          //
						// PRINT RESULTSET TO OUTPUT TEXT BOX HERE  //
						//                                          //
						//                                          //
						//////////////////////////////////////////////.

						//Set the table to hold the values from the ResultSet query
						model = buildTableModel(rs);
						addTableToCenter(resultTable, display_panel, model);

						//setHistoryButtons(); //PART 2

						//table = new JTable(buildTableModel(rs));
						//JOptionPane.showMessageDialog(null, new JScrollPane(table));

						// Close the ResultSet
						rs.close();
						System.out.println("**** Closed JDBC ResultSet");

						// Close the Statement
						stmt.close();
						System.out.println("**** Closed JDBC Statement");

						// Close the connection
						con.close();
						System.out.println("**** Disconnected from data source");

						System.out.println("**** JDBC Exit from class EzJava - no errors");

						sortTime = System.currentTimeMillis() - sortTime;  //duration = end - start time
						//JOptionPane.showMessageDialog(null, "Total query time " + sortTime + " milliseconds.");
						queryTime.setText("Query time: " + sortTime + " milliseconds");
						queryItemsNum.setText("Total items: " + numRows);
					}			

					catch (ClassNotFoundException exception1) {
						System.err.println("Could not load JDBC driver");
						System.out.println("Exception: " + exception1);
						exception1.printStackTrace();
					} catch(SQLException exception2) {
						System.err.println("SQLException information");
						while(exception2!=null) {
							System.err.println ("Error msg: " + exception2.getMessage());
							System.err.println ("SQLSTATE: " + exception2.getSQLState());
							System.err.println ("Error code: " + exception2.getErrorCode());
							exception2.printStackTrace();
							exception2 = exception2.getNextException(); // For drivers that support chained exceptions
						}
					} catch(NumberFormatException nfe) {
						JOptionPane.showMessageDialog(null, "Error:\n" + nfe.getMessage());
					}
					// JDBC CONNECTION AND QUERY	
				}
			}
		});
		generateResultPanel.add(genResultButton);
	}

	/**
	 * 
	 * 
	 * 
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	public static DefaultTableModel buildTableModel(ResultSet rs)
			throws SQLException {

		ResultSetMetaData metaData = rs.getMetaData();

		// names of columns
		Vector<String> columnNames = new Vector<String>();
		int columnCount = metaData.getColumnCount();
		for (int column = 1; column <= columnCount; column++) {
			columnNames.add(metaData.getColumnName(column));
		}

		// data of the table
		Vector<Vector<Object>> data = new Vector<Vector<Object>>();
		while (rs.next()) {
			Vector<Object> vector = new Vector<Object>();
			for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
				vector.add(rs.getObject(columnIndex));
			}
			data.add(vector);
		}

		numRows = data.size();
		return new DefaultTableModel(data, columnNames);
	}

	/**
	 * 
	 * 
	 * 
	 * @param table
	 */
	public void setTableDimensions(JTable table) {

		//Set column widths
		table.setPreferredScrollableViewportSize(new Dimension(650,350));
		TableColumnModel tcm = table.getColumnModel();

		tcm.getColumn(0).setPreferredWidth(700);	//Weapon Name
		tcm.getColumn(1).setPreferredWidth(250);	//Weapon Type
		tcm.getColumn(2).setPreferredWidth(200);	//Weapon Damage
		tcm.getColumn(3).setPreferredWidth(200); 	//Weapon Weight
		tcm.getColumn(4).setPreferredWidth(150); 	//Weapon Value
		tcm.getColumn(5).setPreferredWidth(300); 	//Weapon Rarity
	}

	/**
	 * 
	 * 
	 * 
	 * @param table
	 * @param panel
	 * @param dtm
	 */
	public void addTableToCenter(JTable table, JPanel panel, DefaultTableModel dtm) {
		panel.removeAll(); //Removes everything currently on the panel

		table.setModel(dtm); //Sets the model for the table
		setTableDimensions(table); //Sets table dimensions
		table.setVisible(true);

		JScrollPane scrollPane = new JScrollPane(table); //Add table to a Scroll Pane                  
		panel.add(scrollPane); //Add Scroll Pane to the center panel
		panel.revalidate(); 
	}

	/**
	 * 
	 * 
	 * 
	 * @param table
	 * @param panel
	 */
	public void testOnStartup(JTable table, JPanel panel) {

		String urlPrefix = "jdbc:mysql:";
		String url = urlPrefix + "//128.171.42.110:3306/badass";
		String user = "ics321";
		String password = "badass";
		Connection con;	
		Statement statementTest = null;
		ResultSet rsTest;
		DefaultTableModel testStartup = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");

			// Create the connection using the IBM Data Server Driver for JDBC and SQLJ
			con = DriverManager.getConnection (url, user, password);
			// Commit changes automatically
			con.setAutoCommit(true);

			// Create the Statement
			statementTest = con.createStatement();

			rsTest = statementTest.executeQuery("SELECT Name, Type, Damage, Weight, Value, Rarity FROM weapons ORDER BY Name ASC");
			testStartup = buildTableModel(rsTest);
		} catch (ClassNotFoundException exception1) {
			System.err.println("Could not load JDBC driver");
			System.out.println("Exception: " + exception1);
			exception1.printStackTrace();
		} catch(SQLException exception2 ) {
			System.err.println("SQLException information");
			while(exception2!=null) {
				System.err.println ("Error msg: " + exception2.getMessage());
				System.err.println ("SQLSTATE: " + exception2.getSQLState());
				System.err.println ("Error code: " + exception2.getErrorCode());
				exception2.printStackTrace();
				exception2 = exception2.getNextException(); // For drivers that support chained exceptions
			}
		}
		addTableToCenter(table, panel, testStartup);
	}

	/**
	 * 
	 * 
	 * 
	 * @param inputLocation
	 */
	private void createList(String inputLocation){
		try {
			String[] columnNames = {"Name", "Type", "Damage", "Weight", "Value", "Rarity"};
			model = new DefaultTableModel(columnNames, 0);

			// Creates a url to connect to.
			URL file = new URL(inputLocation);
			// Tries to connect to given url.
			URLConnection path = file.openConnection();
			// Reads in text file.
			BufferedReader in = new BufferedReader(new InputStreamReader(path.getInputStream()));
			// inputLine stores incoming array being read
			String inputLine;
			// Creates array size

			// Creates the array.
			while ((inputLine = in.readLine()) != null){

				String[] splitInput = inputLine.split(" \\| ");
				boolean match = true;

				//Name
				if(match && !getText[0].equals("")) {
					if(splitInput[0].toLowerCase().contains(getText[0]) || splitInput[0].equalsIgnoreCase(getText[0])) {
						//matches, do nothing
					} else {
						// doesn't match, match is now false.
						match = false;
					}
				}

				//Type
				if(match && !getText[1].equals("")) {
					if(splitInput[1].toLowerCase().contains(getText[1]) || splitInput[1].equalsIgnoreCase(getText[1])) {
						//matches, do nothing
					} else {
						// doesn't match, match is now false.
						match = false;
					}
				}

				//Modifier
				if(match && !getText[2].equals("")) {
					if(splitInput[0].toLowerCase().contains(getText[2]) || splitInput[0].equalsIgnoreCase(getText[2])) {
						//matches, do nothing
					} else {
						// doesn't match, match is now false.
						match = false;
					}
				}

				//Attribute
				if(match && !getText[3].equals("")) {
					if(splitInput[0].toLowerCase().contains(getText[3]) || splitInput[0].equalsIgnoreCase(getText[3])) {
						//matches, do nothing
					} else {
						// doesn't match, match is now false.
						match = false;
					}
				}

				//Damage
				if(match && !getText[5].equals("")) {
					int getTextDmg = Integer.parseInt(getText[5]);
					int inputFileDmg = Integer.parseInt(splitInput[2]);

					if(getText[4].equals("<")) {
						if(inputFileDmg > getTextDmg || inputFileDmg == getTextDmg) {
							match = false;
						}
					} else if(getText[4].equals(">")) {
						if(inputFileDmg < getTextDmg || inputFileDmg == getTextDmg) {
							match = false;
						}
					} else {
						if(!getText[5].equals(splitInput[2])) {
							match = false;
						}
					}
				}

				//Weight
				if(match && !getText[7].equals("")) {
					int getTextWeight = Integer.parseInt(getText[7]);
					int inputFileWeight = Integer.parseInt(splitInput[3]);

					if(getText[6].equals("<")) {
						if(inputFileWeight > getTextWeight || inputFileWeight == getTextWeight) {
							match = false;
						}
					} else if(getText[6].equals(">")) {
						if(inputFileWeight < getTextWeight || inputFileWeight == getTextWeight) {
							match = false;
						}
					} else {
						if(!getText[7].equals(splitInput[3])) {
							match = false;
						}
					}
				}

				//Value
				if(match && !getText[9].equals("")) {
					int getTextDmg = Integer.parseInt(getText[9]);
					int inputFileDmg = Integer.parseInt(splitInput[4]);

					if(getText[8].equals("<")) {
						if(inputFileDmg > getTextDmg || inputFileDmg == getTextDmg) {
							match = false;
						}
					} else if(getText[8].equals(">")) {
						if(inputFileDmg < getTextDmg || inputFileDmg == getTextDmg) {
							match = false;
						}
					} else {
						if(!getText[9].equals(splitInput[4])) {
							match = false;
						}
					}
				}

				//Rarity
				if(match && !getText[10].equals("")) {

					if(!getText[10].equals("All")) {
						if(splitInput[5].equals(getText[10])) {
							//matches, do nothing
						} else {
							// doesn't match, match is now false.
							match = false;
						}
					}
				}

				if(match) {
					//URLtableItems.add(inputLine);
					model.addRow(splitInput);
				}

				resultTable = new JTable(model);	
				resultTable.setAutoCreateColumnsFromModel(false);
				Vector<?> data = model.getDataVector();

				//"Name", "Type", "Damage", "Weight", "Value", "Rarity"

				if(!getText[11].equals("")) {
					if(getText[11].equals("Name")) {
						Collections.sort(data, new ColumnSorter(0));
					} else if(getText[11].equals("Type")) {
						Collections.sort(data, new ColumnSorter(1));
					} else if(getText[11].equals("Damage")) {
						Collections.sort(data, new ColumnSorter(2));
					} else if(getText[11].equals("Weight")) {
						Collections.sort(data, new ColumnSorter(3));
					} else if(getText[11].equals("Value")) {
						Collections.sort(data, new ColumnSorter(4));
					} else {
						Collections.sort(data, new ColumnSorter(5));
					}
					model.fireTableStructureChanged();
				}

				addTableToCenter(resultTable, display_panel, model);
			}

			in.close();

			// Catches if any invalid character found in the array.
		} catch (NumberFormatException nfe) {
			// Catches error if no text file is found.
		} catch (Exception e) {
			// Text file is wrong format.
		}
	}

	/**
	 * 
	 *
	 */
	class ColumnSorter implements Comparator<Object> {
		int colIndex;

		/**
		 * 
		 * 
		 * @param colIndex
		 */
		ColumnSorter(int colIndex) {
			this.colIndex = colIndex;
		}

		/**
		 * 
		 * 
		 * 
		 */
		@SuppressWarnings("unchecked")
		public int compare(Object a, Object b) {
			Vector<?> v1 = (Vector<?>) a;
			Vector<?> v2 = (Vector<?>) b;
			Object o1 = v1.get(colIndex);
			Object o2 = v2.get(colIndex);

			if(o1 instanceof String && ((String) o1).length() == 0) {
				o1 = null;
			}
			
			if(o2 instanceof String && ((String) o2).length() == 0) {
				o2 = null;
			}

			if(o1 == null && o2 == null) {
				return 0;
			} else if(o1 == null) {
				return 1;
			} else if (o2 == null) {
				return -1;
			} else if(o1 instanceof Comparable) {
				return ((Comparable<Object>) o1).compareTo(o2);
			} else {
				return o1.toString().compareTo(o2.toString());
			}
		}
	}

}